//
//  WBOAuthViewController.swift
//  TYCWeiBo
//
//  Created by 中发 on 2018/6/6.
//  Copyright © 2018年 中发. All rights reserved.
//

import UIKit
import SVProgressHUD

//通过webView来加载新浪微博授权控制器
class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    override func loadView() {
        
        view = webView
        view.backgroundColor = UIColor.white
        //设置代理
        webView.delegate = self
        //设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill), isBack: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirctURI)"
        
        //1>URL确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        //2>建立请求
        let request = URLRequest(url: url)
        //3>加载请求
        webView.loadRequest(request)
    }
    
    //MARK:监听方法
    @objc func close() {
        dismiss(animated: true, completion: nil)
    }
    @objc func autoFill() {
        
        let js = "document.getElementById('userId').value = 'tang19941118@qq.com'; " + "document.getElementById('passwd').value = 'tang137591'; "
        
        webView.stringByEvaluatingJavaScript(from: js)
    }

}

extension WBOAuthViewController: UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果请求地址包含http://baidu.com，不加载页面/否则加载页面
      print("加载请求---\(request.url?.absoluteString)")
        //从http://baidu.com回调地址中查询字符串code=，如果有，则授权成功，否则授权失败
        if request.url?.absoluteString.hasPrefix(WBRedirctURI) == false {
            return true
        }
        //'quary'就是‘url’中‘？’后面的所有内容
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        //从‘query’中获取授权码，
        //在这里，代码一定有查询字符串，并且包含‘code=’
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("获取授权码...\(code)")
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: self)
                //关闭窗口
                self.close()
            }
        }
        return false
    }
    
}
